package org.sample.net.udp;

import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class UDPClient {

    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private Scanner scanner;

    private DatagramSocket socket;

    private String name;

    private InetAddress targetAddress;

    private Integer targetProt = 8000;

    public UDPClient(String name, InetAddress address) throws Exception {
        this.scanner = new Scanner(System.in);
        try {
            this.socket = new DatagramSocket(targetProt);
        } catch (BindException e) {
            this.socket = new DatagramSocket(targetProt + 1);
        }
        this.name = name;
        this.targetAddress = address;
    }

    public void read() throws Exception {
        byte[] buff = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buff, buff.length);
        while (true) {
            socket.receive(packet);
            targetAddress = packet.getAddress();
            targetProt = packet.getPort();
            System.out.println(new String(buff));
        }
    }

    public void write() throws Exception {
        DatagramPacket packet = null;
        while (scanner.hasNext()) {
            String message = scanner.nextLine();

            StringBuilder sb = new StringBuilder(df.format(new Date()));
            sb.append(" ").append(name).append("\n");
            sb.append(message);
            String msg = sb.toString();
            packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, targetAddress, targetProt);
            socket.send(packet);
        }
    }

    public void close() {
        scanner.close();
        socket.close();
    }

}